package com.ydgg.ltar.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

import com.google.gson.JsonObject;

public class OrderInfoUtil2_0 {

	/**
	 * 构造授权参数列表
	 * 
	 * @param pid
	 * @param app_id
	 * @param target_id
	 * @return
	 */
	public static Map<String, String> buildAuthInfoMap(String pid, String app_id, String target_id) {
		Map<String, String> keyValues = new HashMap<String, String>();

		// 商户签约拿到的app_id，如：2013081700024223
		keyValues.put("app_id", app_id);

		// 商户签约拿到的pid，如：2088102123816631
		keyValues.put("pid", pid);

		// 服务接口名称， 固定值
		keyValues.put("apiname", "com.alipay.account.auth");

		// 商户类型标识， 固定值
		keyValues.put("app_name", "mc");

		// 业务类型， 固定值
		keyValues.put("biz_type", "openservice");

		// 产品码， 固定值
		keyValues.put("product_id", "APP_FAST_LOGIN");

		// 授权范围， 固定值
		keyValues.put("scope", "kuaijie");

		// 商户唯一标识，如：kkkkk091125
		keyValues.put("target_id", target_id);

		// 授权类型， 固定值
		keyValues.put("auth_type", "AUTHACCOUNT");

		// 签名类型
		keyValues.put("sign_type", "RSA");

		return keyValues;
	}

	/**
	 * 构造支付订单参数列表
	 * @param pid
	 * @param app_id
	 * @param target_id
	 * @return
	 * @throws ParseException 
	 */
	public static Map<String, Object> buildOrderParamMap(double total_amount, String timestamp, String body) throws ParseException {
		Map<String, String> keyValues = new HashMap<String, String>();
		Map<String, Object> res = new HashMap<String, Object>();

		String seller_id = "2088421943565793";//正式2088421943565793,2088102177077642
		String out_trade_no = getOutTradeNo();
		
		//返回签名所需信息2016101702208037
		keyValues.put("app_id", "2016101702208037");//正式2016101702208037

		keyValues.put("biz_content", "{\"timeout_express\":\"30m\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"total_amount\":\""+total_amount+"\",\"subject\":\""+body+"\",\"body\":\""+body+"\",\"out_trade_no\":\"" + out_trade_no + "\",\"seller_id\":\""+seller_id+"\"}");
		
		JsonObject json = new JsonObject();
		json.addProperty("timeout_express", "30m");
		json.addProperty("product_code", "QUICK_MSECURITY_PAY");
		json.addProperty("total_amount", total_amount);
		json.addProperty("subject", body);
		json.addProperty("body", body);
		json.addProperty("out_trade_no", out_trade_no);
		json.addProperty("seller_id", seller_id);
		
		keyValues.put("charset", "utf-8");
		keyValues.put("method", "alipay.trade.app.pay");
		keyValues.put("sign_type", "RSA");
		keyValues.put("timestamp", timestamp);
		keyValues.put("version", "1.0");
		keyValues.put("notify_url", "https://ar.zhyell.com/api/aliPay/async");
		
		//返回订单信息
		res.put("out_trade_no", out_trade_no);
		res.put("keyValues", keyValues);
		
		return res;
	}
	
	/**
	 * 构造支付订单参数信息
	 * 
	 * @param map
	 * 支付订单参数
	 * @return
	 */
	public static String buildOrderParam(Map<String, String> map) {
		List<String> keys = new ArrayList<String>(map.keySet());

		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < keys.size() - 1; i++) {
			String key = keys.get(i);
			String value = map.get(key);
			sb.append(buildKeyValue(key, value, true));
			sb.append("&");
		}

		String tailKey = keys.get(keys.size() - 1);
		String tailValue = map.get(tailKey);
		sb.append(buildKeyValue(tailKey, tailValue, true));

		return sb.toString();
	}
	
	/**
	 * 拼接键值对
	 * 
	 * @param key
	 * @param value
	 * @param isEncode
	 * @return
	 */
	static String buildKeyValue(String key, String value, boolean isEncode) {
		StringBuilder sb = new StringBuilder();
		sb.append(key);
		sb.append("=");
		if (isEncode) {
			try {
				sb.append(URLEncoder.encode(value, "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				sb.append(value);
			}
		} else {
			sb.append(value);
		}
		return sb.toString();
	}
	
	/**
	 * 对支付参数信息进行签名
	 * 
	 * @param map
	 *            待签名授权信息
	 * 
	 * @return
	 */
	public static String getSign(Map<String, String> map) {
//		String rsaKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAm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ACXVkOt1gVXPEotMAY0eBgT0zAgMBAAECgYBmDRXODFydriirj3KgUO90fhOG"
			+ "xo4VCo1Wiqjo4BMqNRspE6XtKaG5SA/MCUc5DeZwYD6I0mUTEs8ovdIFF1BYEMDW"
			+ "CVDRPEjCe4P4IQxmvRQTUepw2kRWBRpIfHx5Au0rxp9aBVDysQTo/vcobCjdHQtw"
			+ "pEoUBxaEagzME7btgQJBAOa33J5EI/zkRggFltGi4mlFbniEB+Th9HSezMLdpQh9"
			+ "jLnFhhsmnLWi8GwYVtPMv0tBkFyEx5Dpah7kGJ/dlFMCQQDQL6AMlUrr5jDGML8Y"
			+ "5VlhA6SXe8Drw4iFHde7TY+6Mv1kZPJHl3aujpcu/7p7NJY5xqhTTB/Ve04/Na8z"
			+ "bpehAkEAptnCt8YpjIL9TmHUX0j/mgf3SzqYhuMNqaUKCcbGyewZ8GMzh8EVxZnP"
			+ "ayzy5fsFQIRqxS3VMSxMbYihckOJNwJAAyxmrSptbPEiVzMRBqkgVqk+jgyV4UIm"
			+ "x5iv3CwPf9AdKrWbN9ooNfr4dP/y8MPZcmID2Nk1NwTdKXuBAzCxYQJASbpzPH+d"
			+ "az+CB3NKR/H3uknA7/6uNXZA5d5BCVj5jfJdMhKKDA96sPWYCRyaMQUxNpXm6B4z"
			+ "hL84OMOq1rb9fw==";
		
		List<String> keys = new ArrayList<String>(map.keySet());
		// key排序
		Collections.sort(keys);

		StringBuilder authInfo = new StringBuilder();
		for (int i = 0; i < keys.size() - 1; i++) {
			String key = keys.get(i);
			String value = map.get(key);
			authInfo.append(buildKeyValue(key, value, false));
			authInfo.append("&");
		}

		String tailKey = keys.get(keys.size() - 1);
		String tailValue = map.get(tailKey);
		authInfo.append(buildKeyValue(tailKey, tailValue, false));

		String oriSign = SignUtils.sign(authInfo.toString(), rsaKey);
		String encodedSign = "";

		try {
			encodedSign = URLEncoder.encode(oriSign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "sign=" + encodedSign;
	}
	
	/**
	 * 要求外部订单号必须唯一。
	 * @return
	 */
	public static String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}
	
	public static StringBuilder sort(Map<String, String> map) {
		List<String> keys = new ArrayList<String>(map.keySet());
		// key排序
		Collections.sort(keys);

		StringBuilder authInfo = new StringBuilder();
		for (int i = 0; i < keys.size() - 1; i++) {
			String key = keys.get(i);
			String value = map.get(key);
			authInfo.append(buildKeyValue(key, value, false));
			authInfo.append("&");
		}
		String tailKey = keys.get(keys.size() - 1);
		String tailValue = map.get(tailKey);
		authInfo.append(buildKeyValue(tailKey, tailValue, false));
		return authInfo;
	}

}
